import GoodsSpecSelect from '@/components/GoodsSpecSelect';
import Icon from '@/components/Icon';
import ListEnd from '@/components/ListEnd';
import { ProductImg } from '@/components/product/ProductImg';
import StandProductSort, { SortFilter } from '@/components/product/StandProductSort';
import Search from '@/components/Search';
import { AddressType, getGoodsDefaultSendAddress } from '@/dataTransfer/location';
import { checkProductIsSoldOut } from '@/dataTransfer/product';
import utils from '@/utils';
import { debounce } from '@/utils/helper';
import { useShowLoading } from '@/utils/hooks/useShowLoading';
import { goProductDetailById } from '@/utils/index';
import { ScrollView, View, Text } from '@tarojs/components';
import Taro, { useDidShow, useRouter } from '@tarojs/taro';
import classNames from 'classnames';
import React, { useCallback, useEffect, useState } from 'react';
import { connect } from 'react-redux';
import { noop } from '../../utils/fn';
import './index.scss';

const transformSort = (sort) => {
  if (sort === SortFilter.comprehensive) {
    return {
      orderBy: 'updated',
      direction: 1,
    };
  }

  if (sort === SortFilter.sales) {
    return {
      orderBy: 'saleNumber',
      direction: 1,
    };
  }

  if (sort === SortFilter.up) {
    return {
      orderBy: 'price',
      direction: 0,
    };
  }

  if (sort === SortFilter.down) {
    return {
      orderBy: 'price',
      direction: 1,
    };
  }

  return {};
};

const SalesPromotion = ({
  dispatch,
  loading,
  activityReduces,
  productList,
  productListFinished,
  activityProductAmt = {
    total: 0,
    fullAmount: 0,
    reduceAmount: 0,
  },

  allAddresses,
}) => {
  useShowLoading(loading, ['giftCard/fetchProductList', 'giftCard/fetchActivityReduces']);

  const [sort, setSort] = useState(SortFilter.comprehensive);
  const [keyWords, setKeyWords] = useState('');
  const [selectedAddress, setSelectedAddress] = useState(undefined);

  // 规格选择后显示商品
  const [specProduct, setSpecProduct] = useState();
  const [visible, setVisible] = useState(false);

  const { params: { id } = {} } = useRouter();
  const reduceText = activityReduces
    ?.map(({ fullReduce }) => {
      return fullReduce;
    })
    .join(',');

  const isRebate = !!activityReduces?.length;

  const handleSearch = (keywords) => {
    setKeyWords(keywords);
  };

  // 获取 商品列表
  const getNextList = useCallback(
    (params) => {
      return dispatch({
        type: 'giftCard/fetchProductList',
        payload: {
          pageSize: 10,
          id,
          title: keyWords,
          ...transformSort(sort),
          ...params,
        },
      });
    },
    [id, keyWords, sort],
  );

  // 滚动获取
  const handleScrollToLower = debounce(() => {
    !productListFinished && productList?.length > 0 && getNextList();
  }, 1200);

  const handleSelectSpec = (product) => {
    // 商品无库存
    const isSoldOut = checkProductIsSoldOut(product, 'inventoryQuantity');

    if (isSoldOut) {
      return;
    }

    setSpecProduct({
      ...product,
      storeId: product.orgId,
      id: product.productReleaseId,
      selected: 1,
      mediaList: [{ url: product.url }],
    });

    setTimeout(() => {
      setVisible(true);
    }, 0);
  };

  const getActivityProductAmt = () => {
    dispatch({
      type: 'giftCard/getActivityProductAmt',
      payload: id,
    });
  };

  // 获取所有 收货地址
  useDidShow(() => {
    // 未登录, 不请求
    if (!utils.getToken()) {
      return;
    }

    // 已经存在的地址了, 就不再获取
    if (allAddresses && allAddresses.length) {
      return;
    }
    dispatch({ type: 'giftCard/allAddressesModel', payload: { setDefaultAddress: false } });
  });

  // 获取用户选择地址
  useEffect(() => {
    let list = allAddresses;

    // 如果没有登录, 则获取经纬度, 即把用户地址列表为空数组
    if (!utils.getToken()) {
      list = [];
    }
    if (!list) {
      return;
    }

    // list 为空数组时, 获取的是 当前定位
    // 否则按照 上次选择 => 默认地址 => 当前定位 顺序选择
    getGoodsDefaultSendAddress(dispatch, list)
      .then((data) => {
        setSelectedAddress(data);
      })
      .catch((e) => {
        console.warn(e);

        setSelectedAddress({ type: AddressType.failed });
      });
  }, [allAddresses]);

  // 获取满减列表
  useEffect(() => {
    dispatch({
      type: 'giftCard/fetchActivityReduces',
      payload: id,
    });
  }, [id]);

  // 获取 商品列表
  useEffect(() => {
    getNextList({ page: 1 });
  }, [id, keyWords, sort]);

  // 获取在购物车中的适合这次优惠券的商品总价
  // 每次页面显示时重新获取
  useDidShow(() => {
    if (!utils.getToken()) {
      return;
    }

    getActivityProductAmt();
  });

  return (
    <View className="SalesPromotion">
      {specProduct && (
        <GoodsSpecSelect
          visible={visible}
          setVisible={setVisible}
          needSkuBy="sku"
          dispatch={dispatch}
          getSkuSel={noop}
          productDetail={specProduct ?? {}}
          curProduct={{}}
          selectedAddress={selectedAddress}
          curOptions={[]}
          add2cartSuccess={getActivityProductAmt}
        />
      )}

      <View className="search-container customePageStyle">
        <Search defaultValue={keyWords} handleSearch={handleSearch} />
      </View>

      <StandProductSort
        {...{
          value: sort,
          onChange: setSort,
        }}
      />

      <View className="products-wrap">
        <View className="background-wrap">
          <View className="background-1 customePageBackgroundStyle"></View>
          <View className="background-2 customeSalesPromotionProductListBackgroundStyle"></View>
        </View>

        {isRebate ? <View className="tip omit">限时促销：{reduceText}</View> : null}

        <ScrollView
          enableFlex
          scrollY
          style={{
            display: 'flex',
            flexDirection: 'column',
            height: utils.getCalcHeight(
              {},
              // 搜索框
              98,
              // 筛选
              92,
              // 满减 tip
              isRebate ? 96 : 0,

              // 底部去购买
              98,
              // 底部 tip 提醒
              0,
              // 底部菜单
              Taro.$bottomHight ? 68 : 0,
            ),
          }}
          onScrollToLower={handleScrollToLower}
        >
          <View className={classNames('product-list', { off: !isRebate })}>
            {productList?.map((product, index) => {
              const { title, price, originalPrice, url, stock } = product;

              const [p1, p2] = parseFloat(price ?? originalPrice)
                .toFixed(2)
                .split('.');

              const underlinePrice = parseFloat(originalPrice).toFixed(2);

              const isSoldOut = checkProductIsSoldOut(stock);

              return (
                <View
                  className="product-item"
                  key={index}
                  onClick={() => {
                    return goProductDetailById(product.productReleaseId);
                  }}
                >
                  <ProductImg className="left" {...{ url, isSoldOut }} />

                  <View className="right">
                    <View className="title omit-1">{title}</View>

                    {/* <View className="intro omit-1">{subTitle}</View> */}

                    {isRebate && (
                      <View className="line-2">
                        <View className="label label-rect customePageStyleBg15">
                          <View className="txt customePageStyle omit-1">
                            {activityReduces?.[0]?.fullReduce}
                          </View>
                        </View>
                      </View>
                    )}

                    <View className={classNames('line-3 customePageStyle', { rebate: isRebate })}>
                      <View className={classNames('price', { rebate: isRebate })}>
                        <View className="price-1">¥{p1}</View>
                        <View className="price-2">.{p2}</View>
                      </View>

                      {/* 折扣显示划线价 */}
                      {!isRebate && <View className="underline-price">¥{underlinePrice}</View>}
                    </View>
                  </View>

                  <View
                    className=""
                    onClick={(e) => {
                      e.stopPropagation();
                    }}
                  >
                    <Icon
                      name="icon_shopping"
                      className="cart customePageStyle"
                      size={35}
                      onClick={() => {
                        // 使用 promise 延迟下, 让 SpecProduct 先为空
                        // GoodsSpecSelect 组件销毁后重新创建
                        // 防止数据存在混乱
                        new Promise((resolve) => {
                          setSpecProduct(undefined);

                          resolve();
                        }).then(() => {
                          handleSelectSpec(product);
                        });

                        return false;
                      }}
                    />
                  </View>
                </View>
              );
            })}

            {productListFinished && productList?.length > 8 && (
              <ListEnd txt="已无更多该促销相关商品" />
            )}

            <View className="placeholder-block"></View>
          </View>
        </ScrollView>
      </View>

      <View className={classNames('bottom-wrap', { bottomHeight: Taro.$bottomHight })}>
        <View className="line">
          <View className="left">
            {isRebate ? (
              <View className="flex-column-spaceBetween">
                <View className="flex-row--center priceLine">
                  <View className="label">合计：</View>
                  <View className="price customePageStyle">
                    ¥{parseFloat(activityProductAmt.total).toFixed(2)}
                  </View>
                </View>
                {activityProductAmt.total > 0 ? (
                  activityProductAmt.fullAmount > 0 ? (
                    <View className="info">
                      再买
                      <Text className="sep">
                        {parseFloat(activityProductAmt.fullAmount).toFixed(2)}
                      </Text>
                      元，可享受满减优惠
                    </View>
                  ) : (
                    <View className="info">
                      可立减¥
                      <Text className="sep">
                        {parseFloat(activityProductAmt.reduceAmount).toFixed(2)}
                      </Text>
                    </View>
                  )
                ) : (
                  <View className="tip">活动进行中，快去选购商品吧</View>
                )}
              </View>
            ) : (
              <View className="tip">实际优惠金额以结算页为准</View>
            )}
          </View>

          <View
            className="right customePageBackgroundStyle"
            onClick={() => {
              Taro.navigateTo({ url: '/pages/mainPages/cartSin/index' });
            }}
          >
            <View className="txt">去购物车</View>
          </View>
        </View>
      </View>
    </View>
  );
};

export default connect(({ loading, giftCard }) => ({
  loading,
  activityReduces: giftCard.activityReduces,
  activityProductList: giftCard.activityProductList,
  activityProductListFinished: giftCard.activityProductListFinished,
  activityProductAmt: giftCard.activityProductAmt,

  allAddresses: giftCard.allAddresses,

  productList: giftCard.productList,
  productListFinished: giftCard.productListFinished,
}))(SalesPromotion);
